package com.example.ktdemo.ctxobserver.base;

import android.content.Context;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;

import com.example.ktdemo.ctxobserver.api.ContentObserverApi;
import com.example.ktdemo.ctxobserver.bean.ObserverChangeInfo;
import com.example.ktdemo.ctxobserver.listener.ObserverChangeListener;
import com.example.ktdemo.ctxobserver.type.UriType;

/**
 * FileName: ContentBaseObserver
 * Author: lzt
 * Date: 2023/4/28 10:39
 */
public abstract class ContentBaseObserver extends ContentObserver implements ContentObserverApi {
    private final Context mContext;
    private ObserverChangeListener mListener;

    public ContentBaseObserver(Context context, Handler handler, ObserverChangeListener listener) {
        super(handler);
        this.mContext = context;
        this.mListener = listener;
        init();
    }


    protected Context getBaseContext() {
        if (this.mContext == null) {
            throw new NullPointerException("context has no init");
        }
        return this.mContext;
    }

    /**
     * 通知变动
     */
    protected void notifyChange(UriType type, boolean selfChange, Uri uri) {
        if (this.mListener == null) {
            return;
        }
        ObserverChangeInfo info = new ObserverChangeInfo(type, selfChange, uri);
        this.mListener.change(info);
    }

    protected abstract void init();

    @Override
    public void release() {
        this.mListener = null;
    }
}
